package com.example.teacher.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commonutils.ResultData;
import com.example.servicebase.exceptionhandler.CustomException;
import com.example.teacher.entity.EduCourse;
import com.example.teacher.entity.EduCourseDescription;
import com.example.teacher.entity.EsCourseInfo;
import com.example.teacher.entity.Teacher;
import com.example.teacher.entity.course.CourseInfo;
import com.example.teacher.entity.frontvo.CourseFrontVo;
import com.example.teacher.entity.frontvo.CourseWebVo;
import com.example.teacher.entity.vo.CourseInfoVo;
import com.example.teacher.entity.vo.CoursePublishVo;
import com.example.teacher.entity.vo.CourseQuery;
import com.example.teacher.mapper.EduCourseMapper;
import com.example.teacher.service.*;
import io.netty.util.internal.StringUtil;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-05-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    private RestHighLevelClient client;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private EduChapterService chapterService;

    //  添加课程基本信息
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1.向课程表添加课程基本信息
        EduCourse eduCourse=new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert<=0){//添加失败
            throw new CustomException(20001,"课程表添加信息失败");
        }

        //向课程简介表添加课程简介
        EduCourseDescription courseDescription=new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //将id设置为上面的课程id
        courseDescription.setId(eduCourse.getId());
        courseDescriptionService.save(courseDescription);
        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo=new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        //查询简介表
        EduCourseDescription byId = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(byId.getDescription());

        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //修改课程表
        EduCourse eduCourse=new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update==0){
            throw new CustomException(20001,"修改失败");
        }
        EduCourseDescription courseDescription=new EduCourseDescription();
        courseDescription.setId(courseInfoVo.getId());
        courseDescription.setDescription(courseDescription.getDescription());
        courseDescriptionService.updateById(courseDescription);
    }

    @Override
    public CoursePublishVo publishCourseInfo(String courseId) {
        CoursePublishVo publishInfo = baseMapper.getPublishInfo(courseId);
        return publishInfo;
    }

    @Override
    public void removeCourse(String courseId) {
        //先删除小节
        videoService.removeByCourseId(courseId);
        //删除章节
        chapterService.removeByCourseId(courseId);
        //删除简介
        courseDescriptionService.removeById(courseId);
        //删除课程
        int delete = baseMapper.deleteById(courseId);
        if (delete==0){
            throw new CustomException(20001,"删除失败");
        }
    }

    //条件查询带分页查询课程
    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> wrapper =new QueryWrapper<>();
        if (!StringUtil.isNullOrEmpty(courseFrontVo.getSubjectParentId())){
            //一级分类存在
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if (!StringUtil.isNullOrEmpty(courseFrontVo.getSubjectId())){
            //二级分类存在
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if (!StringUtil.isNullOrEmpty(courseFrontVo.getBuyCountSort())){
            //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtil.isNullOrEmpty(courseFrontVo.getGmtCreateSort())){
            //最新
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtil.isNullOrEmpty(courseFrontVo.getGmtCreateSort())){
            //价格
            wrapper.orderByDesc("price");
        }
        baseMapper.selectPage(pageParam, wrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo getCourseBaseInfo(String courseId) {
        return baseMapper.getCourseBaseInfo(courseId);
    }

//    @Override
//    public void insertById(String id) {
//        client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.241.128:9200")));
//        //根据id从数据库中查询出数据
//        EduCourse eduCourse = baseMapper.selectById(id);
//        EsCourseInfo esCourseInfo =new EsCourseInfo();
//        //复制属性
//        BeanUtils.copyProperties(eduCourse,esCourseInfo);
//        //准备reque
//        IndexRequest request =new IndexRequest("onlinelearn").id(esCourseInfo.getId());
//        //准备json文档
//        request.source(JSON.toJSONString(esCourseInfo), XContentType.JSON);
//        try {
//            client.index(request, RequestOptions.DEFAULT);
//            client.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    @Override
//    public void deleteById(String id) {
//        client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.241.128:9200")));
//        DeleteRequest request =new DeleteRequest("onlinelearn",id);
//        try {
//            client.delete(request,RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    @Override
    public void updateViewCount(String courseId) {
        baseMapper.viewCountAdd(courseId);
    }

    @Override
    public ResultData getCourseCondition(Page<EduCourse> pageCourse, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> wrapper=new QueryWrapper<>();
        String courseName = courseQuery.getCourseName();
        String status = courseQuery.getStatus();
        if (!StringUtils.isEmpty(courseName)){
            wrapper.like("title","%"+courseName+"%");
        }
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
//      根据创建时间排序
        wrapper.orderByDesc("gmt_create");
        courseService.page(pageCourse,wrapper);
        List<EduCourse> records = pageCourse.getRecords();
        //封装我们成我们需要的样子
        List<CourseInfo> list=new ArrayList<>();
        for (EduCourse record : records) {
            CourseInfo courseInfo=new CourseInfo();
            BeanUtils.copyProperties(record,courseInfo);
            Teacher teacher = teacherService.getTeacherById(record.getTeacherId());
            courseInfo.setTeacherName(teacher.getName());
            list.add(courseInfo);
        }
        long total = pageCourse.getTotal();
        return ResultData.ok().data("total",total).data("rows",list);
    }
}
